﻿<template>
  <div :id="id" class="scroll-wrap" v-bind="$attrs">
    <div class="scroll-item">
      <div class="scroll-body">
        <slot></slot>
      </div>
    </div>
    <div class="scroll-wrap-body">
      <slot></slot>
    </div>
  </div>
</template>

<script lang="ts">
export default {
  props: {
    startTime: {
      type: Number,
      default: 1000,
    }
  },
  data() {
    return {
      id: `scroll_${new Date().getTime()}_${parseInt(Math.random() * 100000 + '')}`,
      timeoutId: 0,
    }
  },
  methods: {
    /**
     * 计算位置
     */
    getBoxAnimation() {
      let el = document.querySelector(`#${this.id}`) as HTMLElement;
      let contentEl = document.querySelector(`#${this.id} .scroll-item`) as HTMLElement;
      //获取高度 
      const boxHeight = el.offsetHeight || el.clientHeight || 200;
      let contentHeight = contentEl.offsetHeight || contentEl.clientHeight || 200;
      if (boxHeight >= contentHeight) {
        return;
      }
      console.log(contentEl.innerHTML)
      contentEl.innerHTML += contentEl.innerHTML + contentEl.innerHTML + contentEl.innerHTML;
      contentHeight = contentEl.offsetHeight || contentEl.clientHeight || 200;
      //计算动画速度
      let duration = Math.round(contentHeight / boxHeight) * 2 * 1.5;
      duration = duration % 2 != 0 ? duration + 1 : duration;
      contentEl.setAttribute('style', `--scroll-duration:${duration}s;--scroll-height:${boxHeight}px`)
      contentEl.className += ' scroll-item-animation';
    }
  },
  mounted() {
    clearTimeout(this.timeoutId);
    this.timeoutId = setTimeout(() => {
      debugger
      this.getBoxAnimation();
    }, this.startTime);
  },
  destroyed() {
    clearTimeout(this.timeoutId);
  }
}
</script>

<style lang="scss" scoped>
.scroll-wrap {
  overflow: hidden;
  --scroll-default-content-display: none;

  .scroll-item-animation {
    --scroll-height: 200px;
    --scroll-duration: 4s;
    animation: scroll-player linear 10s infinite;
    animation-duration: calc(var(--scroll-duration));
  }

  .scroll-item-animation:hover {
    animation-play-state: paused;
  }

  &:hover {
    .scroll-item {
      display: none;
    }

    .scroll-wrap-body {
      display: block;
      overflow: auto !important;
    }
  }

  .scroll-wrap-body {
    height: 100%;
    display: none;
    overflow: auto !important;
  }
}

@keyframes scroll-player {
  0% {
    transform: translate3d(0, -25%, 0);
  }

  100% {
    transform: translate3d(0, -75%, 0);
  }
}
</style>

